package com.lyj.controller;

import com.lyj.pojo.Result;
import com.lyj.pojo.Device;
import com.lyj.pojo.dto.DeviceAddDTO;
import com.lyj.pojo.dto.DeviceEditDTO;
import com.lyj.pojo.vo.AvailableDeviceVO;
import com.lyj.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    /**
     * 获取设备列表
     */
    @GetMapping("/list")
    public Result getDeviceList(
            @RequestParam Integer familyId,
            @RequestParam(required = false) Integer roomId) {
        List<Device> deviceList = deviceService.getDeviceList(familyId, roomId, 1);
        return Result.success(deviceList);
    }

    /**
     * 编辑设备
     */
    @PutMapping("/edit")
    public Result editDevice(@Valid @RequestBody DeviceEditDTO deviceEditDTO) {
        deviceService.editDevice(deviceEditDTO);
        return Result.success("设备修改成功");
    }

    /**
     * 删除设备
     */
    @DeleteMapping("/{deviceId}")
    public Result deleteDevice(
            @PathVariable Integer deviceId,
            @RequestParam Integer familyId) {
        deviceService.deleteDevice(deviceId, familyId);
        return Result.success("设备删除成功");
    }

    /**
     * 获取家庭内所有设备
     */
    @GetMapping("/available")
    public Result getAvailableDevices(@RequestParam Integer familyId) {
        List<AvailableDeviceVO> devices = deviceService.getAvailableDevices(familyId);
        return Result.success(devices);
    }

    /**
     * 添加设备（将离线设备标记为在线）
     */
    @PostMapping("/add")
    public Result addDevice(@Valid @RequestBody DeviceAddDTO deviceAddDTO) {
        Device device = deviceService.activateOfflineDevice(deviceAddDTO);
        Map<String, Object> result = new HashMap<>();
        result.put("deviceId", device.getDeviceId());
        result.put("is_online", device.getIsOnline());
        return Result.success(result);
    }

    @PostMapping("/{deviceId}/toggle-power")
    public Result togglePower(
            @PathVariable Integer deviceId,
            @RequestParam Integer familyId) {
        Integer newStatus = deviceService.togglePowerStatus(deviceId, familyId);
        Map<String, Integer> result = new HashMap<>();
        result.put("power_status", newStatus);
        return Result.success(result);
    }
}